package com.cpecc.quartz;

import java.util.Date;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cpecc.dao.system.DepDao;
import com.cpecc.dao.system.LDAPDao;
import com.cpecc.dao.system.RoleDao;
import com.cpecc.dao.system.ToDoDao;
import com.cpecc.dao.system.UserDao;
import com.cpecc.model.system.LDAP;
import com.cpecc.model.system.ToDo;
import com.cpecc.model.system.User;

@Service
public class UserSynSchedule {
	
	private String url;
	
	private String adminName;
	
	private String adminPassword;
	
	private String searchBase;
	
	private LdapContext ctx = null;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private LDAPDao ldapDao;
	
	@Autowired
	private DepDao depDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private ToDoDao toDoDao;

	public UserSynSchedule() {		
		
	}
	
	private void initLdap(){
		
		LDAP ldap=ldapDao.getLDAP();
		this.url=ldap.getUrl();
		this.adminName=ldap.getAdminName();
		this.adminPassword=ldap.getAdminPassword();
		this.searchBase=ldap.getSearchBase();
		
		String url=this.url;
		String adminName=this.adminName;
		String adminPassword=this.adminPassword;
		Hashtable<String,String> hashEnv = new Hashtable<String,String>();
		hashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别
		hashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User
		hashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password
		hashEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
		hashEnv.put(Context.PROVIDER_URL, url);
		try {
			ctx = new InitialLdapContext(hashEnv, null);
			//System.out.println("初始化ldap成功！");
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	private void closeLdap() {
		try {
			this.ctx.close();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("rawtypes")
	private void getADInfo(String type, String filter) {
		try {
			//域节点
			String searchBase = this.searchBase;
			// LDAP搜索过滤器类
			// cn=*name*模糊查询 cn=name 精确查询
			String searchFilter = "(objectClass="+type+")";	
			// 创建搜索控制器
			SearchControls searchCtls = new SearchControls();
			// 设置搜索范围
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			String returnedAtts[] = {"name","sAMAccountName"}; //定制返回属性
			searchCtls.setReturningAttributes(returnedAtts); //设置返回属性集			
			//根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
			NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);// Search for objects using the filter
			while (answer.hasMoreElements()) {// 遍历结果集
				SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN				
				User user=new User();
				Attributes attrs = sr.getAttributes();// 得到符合条件的属性集
				if (attrs != null) {
					try {
						for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
							Attribute attr = (Attribute) ne.next();// 得到下一个属性
							//读取属性值
							for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
								String attrName=attr.getID().toString();
								String attrValue=e.next().toString();
								if(attrName.equals("name")){
									user.setName(attrValue);
								}else if(attrName.equals("sAMAccountName")){
									user.setEmail(attrValue+"@cpecc.net");
									user.setUserName(attrValue);
									user.setPassword("123%abc");
									user.setDep(depDao.getDep("888888"));
									user.setRole(roleDao.getRole("6"));
								}
							}							
						}
					} catch (NamingException e) {
						e.printStackTrace();
					}
				}
				if(userDao.findByUsername1(user.getUserName())==null){
					if(user.getEmail()!=null && !user.getEmail().equals("")){
						userDao.save1(user);
						
						for(User user1:userDao.getGZGLY1()){
							ToDo toDo=new ToDo();
							toDo.setCreateDate(new Date());
							toDo.setTask("人员同步");
							toDo.setType("人员同步");
							toDo.setUser(user1);
							toDo.setXinRenId(user.getId());
							toDoDao.save1(toDo);
						}
					}	
				}
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public void userSyn(){
		initLdap();
		getADInfo("user","cn");
		closeLdap();
	}
}
